package com.yyx.app1.tool.SQLite;

/**
 * Created by yuexing on 2015/8/27.
 */
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;


public class Base_SQLiteOperation {
    private PersonSQLiteOpenHelper helper;
    private String tableName;

    public Base_SQLiteOperation(Context context, String dbName, String tableName) {
        this.helper = new PersonSQLiteOpenHelper(context,dbName,tableName);
        this.tableName=tableName;
        SQLiteDatabase db =helper.getWritableDatabase();
        helper.onCreate(db);
        db.close();
    }

    public Base_SQLiteOperation() {
    }

    public long add(String name, int number) {
        SQLiteDatabase db =helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name",name);
        values.put("value", number);
        long result = db.insert(tableName,null,values);
        db.close();
        return result;
    }


    public boolean find(String name) {
        SQLiteDatabase db =helper.getWritableDatabase();
        Cursor cursor = db.query(tableName, null, "name=?", new String[]{name}, null, null, null);
        boolean result = cursor.moveToNext();
        cursor.close();
        db.close();
        return result;
    }

    public int update(String name, int number) {
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("value", number);
        int count = db.update(tableName,values,"name=?",new String[]{name});
        db.close();
        return count;
    }


    public int delete(String name) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int count = db.delete(tableName, "name=?", new String[]{name});
        db.close();
        return count;
    }

    public List<PersonOne> findAll() {
        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cursor = db.query(tableName, new String[]{"number","name", "value"}, null, null, null, null, null);
        List<PersonOne> list = new ArrayList<>();
        while (cursor.moveToNext())
        {
            PersonOne personOne = new PersonOne();
            personOne.setNumber(cursor.getInt(cursor.getColumnIndex("number")));
            personOne.setName(cursor.getString(cursor.getColumnIndex("name")));
            personOne.setValue(cursor.getInt(cursor.getColumnIndex("value")));
            list.add(personOne);
        }
        cursor.close();
        db.close();
        return list;
    }
    public String findAllToString()
    {
        List<PersonOne> list = findAll();
        StringBuilder sb = new StringBuilder();
        for (PersonOne it :list)
        {
            sb.append(it.toString() + "\n");
        }
        Log.i("MESSAGE", sb.toString());
        return sb.toString();
    }
}